package com.blog.util;

import java.io.File;
import java.io.IOException;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

public class XmlValidator {

	public static boolean validate(String xsdPath,String xmlPath){
		boolean flag=false;
		String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		xsdPath = basePath + xsdPath;
		xmlPath = basePath + xmlPath;
		try {
			//创建一个模式工厂；
			SchemaFactory sf=
					SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
			//路径由XML schema文件创建；
			File f=new File(xsdPath);
			Schema s = sf.newSchema(f);
			//创建一个验证程序;
			Validator v=s.newValidator();
			Source so=new StreamSource(xmlPath);
			v.validate(so);
			flag=true;
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (SAXException e) {
			e.printStackTrace();
		}
		//如果正确的话，证明.xml和.xsd文件正确；
		return flag;
	}
	/*测试
	public static void main(String[] args) {
		String xmlPath="database.conf.xml";
		String xsdPath="database.conf.xsd";
		System.out.println(XmlValidator.validate(xsdPath, xmlPath));
	}
	*/
}

